package xyz.csmcool.imoss.service.impl;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import xyz.csmcool.imoss.config.UploadTypeEnum;
import xyz.csmcool.imoss.entity.OssConfig;
import xyz.csmcool.imoss.mapper.OssConfigMapper;
import xyz.csmcool.imoss.service.UploadFile;
import xyz.csmcool.imoss.utils.NameUtil;

import java.io.File;

/**
 * @author 什锦
 * @Package xyz.csmcool.imoss.service.impl
 * @since 2022/8/5 14:34
 */

@Component
@RequiredArgsConstructor
public class AliUpload implements UploadFile {

    final OssConfigMapper ossConfigMapper;

    @Override
    public UploadTypeEnum getUploadType() {
        return UploadTypeEnum.ALI;
    }


    @Override
    public String upload(File file, String prefix2) {
        String endpoint = null;
        String bucketName = null;
        String objectName = null;
        OSS ossClient = null;
        try {
            OssConfig ossConfig = ossConfigMapper.selectConfig();
            endpoint = ossConfig.getRegion();
            String accessKeyId = ossConfig.getSecretId();
            String accessKeySecret = ossConfig.getSecretKey();
            bucketName = ossConfig.getBucketName();
            String prefix = ossConfig.getPrefix();
            objectName = prefix + prefix2 +NameUtil.generateUniqueName(file.getName());

            // 创建OSSClient实例。
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            ossClient.putObject(bucketName, objectName, file);
        } catch (OSSException | ClientException e) {
            e.printStackTrace();
            return null;
        } finally {
            // 关闭OSSClient。
            ossClient.shutdown();
        }
        String url="https://"+bucketName+"."+endpoint+"/" + objectName;
        return url;
    }
}
